package ThreadPool.lagou.concurrent.completableFuture.demo01;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description:
 *  1.需求
 *      1.1 同一款产品，同时搜索出同款产品在各大电商平台的售价
 *      1.2 同一款产品，同时搜索出本产品在同一电商平台下，各个入驻卖家的售价是多少
 * @date 2022/10/7 11:50
 */
public class CompletableFutureMallDemo {

    private  final List<NetMall> list = Arrays.asList(
            new NetMall("jd"),
            new NetMall("dangdang"),
            new NetMall("taobao"),
            new NetMall("pdd")
    );

    public static List<String> getPrice(List<NetMall> list,String productName){
        List<String> collect = list.stream().map(netMall -> String.format(productName + "in %s price is %.2f"
                , netMall.getNetMallName(), netMall.getPrice(productName))).collect(Collectors.toList());
        return collect;
    }

    public static List<String> getPriceByCompletableFuture(List<NetMall> list,String productName){
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        return list.stream().map(netMall -> CompletableFuture.supplyAsync(() ->
                        String.format(productName + "in %s price is %.2f"
                                , netMall.getNetMallName(), netMall.getPrice(productName))
                        ,executorService
                ))
                .collect(Collectors.toList())
                .stream()
                .map(s -> s.join())
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {

        List<String> mysql = getPriceByCompletableFuture(new CompletableFutureMallDemo().list, "mysql");
        System.out.println(mysql);
    }

    class NetMall{
        private String netMallName;

        public String getNetMallName() {
            return netMallName;
        }

        public NetMall(String netMallName) {
            this.netMallName = netMallName;
        }

        public BigDecimal getPrice(String productName){
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return  BigDecimal.valueOf(ThreadLocalRandom.current().nextDouble()*2+productName.charAt(0));
        }
    }
}
